<template>
  <div class="preview-page">
    <div class="control-panel">
      <div class="drive-selector">
        <el-radio-group v-model="currentDrive" @change="handleDriveChange">
          <el-radio-button 
            v-for="drive in drives" 
            :key="drive.path"
            :label="drive.path"
            :disabled="!drive.available"
          >
            {{ drive.label }}
            <span class="drive-info">{{ formatFileSize(drive.freeSpace) }} 可用</span>
          </el-radio-button>
        </el-radio-group>
      </div>
      <div class="favorite-paths">
        <el-dropdown trigger="click">
          <el-button type="primary" :icon="Star">
            常用路径
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                v-for="path in favoritePaths"
                :key="path.id"
                @click="fetchFiles(path.path)"
              >
                <el-space>
                  <el-icon><Folder /></el-icon>
                  <span>{{ path.name }}</span>
                  <el-button
                    type="danger"
                    link
                    :icon="Delete"
                    @click.stop="deleteFavoritePath(path.id)"
                  />
                </el-space>
              </el-dropdown-item>
              <el-dropdown-item divided>
                <el-button
                  type="primary"
                  link
                  :icon="Plus"
                  @click="showAddPathDialog"
                >
                  添加常用路径
                </el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <el-switch
        v-model="showHidden"
        class="show-hidden-switch"
        active-text="显示隐藏文件"
      />
    </div>

    <el-row :gutter="20" class="content-area">
      <el-col :span="10">
        <el-card class="file-list">
          <template #header>
            <div class="card-header">
              <el-button-group>
                <el-button 
                  type="primary" 
                  :icon="Back" 
                  size="small"
                  @click="navigateUp"
                  :disabled="currentPath === DEFAULT_PATH"
                >
                  返回上级
                </el-button>
                <el-button 
                  type="primary" 
                  :icon="Refresh" 
                  size="small"
                  @click="refreshFiles"
                  :loading="loading"
                >
                  刷新
                </el-button>
              </el-button-group>
            </div>
          </template>

          <div class="current-path">
            当前路径: {{ currentPath }}
          </div>

          <el-scrollbar height="calc(100vh - 250px)">
            <el-table
              v-loading="loading"
              :data="filteredFileList"
              style="width: 100%"
              :default-sort="{ prop: 'is_dir', order: 'descending' }"
              @row-click="handleFileClick"
              @row-dblclick="handleFileDblClick"
            >
              <el-table-column width="50">
                <template #default="{ row }">
                  <el-icon>
                    <component :is="getFileIcon(row)" />
                  </el-icon>
                </template>
              </el-table-column>
              <el-table-column 
                prop="name" 
                label="名称" 
                min-width="200"
                sortable
              >
                <template #default="{ row }">
                  <span :class="{ 'is-folder': row.is_dir }">{{ row.name }}</span>
                </template>
              </el-table-column>
              <el-table-column 
                prop="size" 
                label="大小" 
                width="120"
                align="right"
                sortable
              >
                <template #default="{ row }">
                  {{ row.is_dir ? '-' : formatFileSize(row.size) }}
                </template>
              </el-table-column>
              <el-table-column 
                prop="modified" 
                label="修改时间" 
                width="180"
                sortable
              >
                <template #default="{ row }">
                  {{ formatDate(row.modified * 1000) }}
                </template>
              </el-table-column>
              <el-table-column 
                label="操作" 
                width="150"
                fixed="right"
              >
                <template #default="{ row }">
                  <el-button-group>
                    <el-button
                      type="primary"
                      link
                      :icon="Edit"
                      @click.stop="handleRename(row)"
                    >
                      重命名
                    </el-button>
                    <el-button
                      type="danger"
                      link
                      :icon="Delete"
                      @click.stop="handleDelete(row)"
                    >
                      删除
                    </el-button>
                  </el-button-group>
                </template>
              </el-table-column>
            </el-table>
          </el-scrollbar>
        </el-card>
      </el-col>

      <el-col :span="14">
        <el-card class="preview-area">
          <template #header>
            <div class="card-header">
              <div class="preview-title">
                <span>{{ getPreviewTitle }}</span>
                <el-tag 
                  v-if="currentFile && !currentFile.is_dir" 
                  :type="getFileExtensionTagType"
                  size="small"
                  class="file-extension"
                >
                  {{ getFileExtension }}
                </el-tag>
              </div>
              <div v-if="currentFile && !currentFile.is_dir">
                <el-button-group>
                  <el-button 
                    type="primary" 
                    :icon="Download" 
                    size="small"
                    @click="handleDownload"
                  >
                    下载
                  </el-button>
                  <el-button 
                    type="primary" 
                    :icon="FolderOpened" 
                    size="small"
                    @click="openInExplorer"
                  >
                    打开位置
                  </el-button>
                </el-button-group>
              </div>
            </div>
          </template>

          <!-- 空状态 -->
          <div v-if="!currentFile" class="empty-preview">
            <el-empty description="请选择要预览的文件或文件夹" />
          </div>

          <!-- 文件夹预览 -->
          <template v-else-if="currentFile.is_dir">
            <div class="folder-preview">
              <el-row :gutter="20">
                <el-col 
                  v-for="item in filteredFolderContents" 
                  :key="item.file_path"
                  :span="6"
                >
                  <div 
                    class="file-item"
                    @click="handlePreviewItem(item)"
                    @dblclick="handleFileDblClick(item)"
                  >
                    <!-- 图片文件显示缩略图 -->
                    <template v-if="item.file_type === 'image'">
                      <div class="thumbnail">
                        <el-image 
                          :src="`/api/file-system/thumbnail?path=${encodeURIComponent(item.file_path)}`"
                          :preview-src-list="folderImageUrls"
                          :initial-index="getFolderImageIndex(item)"
                          preview-teleported
                          :hide-on-click-modal="true"
                          fit="cover"
                          @click.stop
                        />
                      </div>
                    </template>
                    <!-- 其他文件显示 -->
                    <template v-else>
                      <el-icon :size="40">
                        <component :is="getFileIcon(item)" />
                      </el-icon>
                    </template>
                    <div class="file-info-wrapper">
                      <div class="file-name" :title="item.name">
                        {{ getFileNameWithoutExt(item.name) }}
                      </div>
                      <el-tag 
                        v-if="!item.is_dir"
                        size="small"
                        :type="getFileExtensionType(item.file_type)"
                        class="file-ext-tag"
                      >
                        {{ getFileExt(item.name) }}
                      </el-tag>
                    </div>
                    <div class="file-info">
                      <span>{{ item.is_dir ? '-' : formatFileSize(item.size) }}</span>
                      <span>{{ formatDate(item.modified * 1000) }}</span>
                    </div>
                  </div>
                </el-col>
              </el-row>
            </div>
          </template>

          <!-- 文件预览 -->
          <div v-else class="file-preview">
            <!-- 图片预览 -->
            <template v-if="currentFile.file_type === 'image'">
              <div class="image-preview">
                <div class="image-actions">
                  <el-button 
                    circle 
                    :icon="ArrowLeft"
                    @click="showPrevImage"
                    :disabled="!hasPrevImage"
                  />
                  <el-image 
                    :src="`/api/file-system/content?path=${encodeURIComponent(currentFile.file_path)}`"
                    :preview-src-list="[`/api/file-system/content?path=${encodeURIComponent(currentFile.file_path)}`]"
                    preview-teleported
                    :hide-on-click-modal="true"
                    fit="contain"
                  />
                  <el-button 
                    circle 
                    :icon="ArrowRight"
                    @click="showNextImage"
                    :disabled="!hasNextImage"
                  />
                </div>
                <div class="image-info">
                  {{ currentImageIndex + 1 }} / {{ totalImages }}
                </div>
              </div>
            </template>
            <!-- 文本预览 -->
            <template v-else-if="currentFile.file_type === 'text'">
              <div class="text-preview">
                <pre v-if="previewContent">{{ previewContent }}</pre>
                <div v-else class="loading-text">
                  <el-icon class="is-loading"><Loading /></el-icon>
                  加载中...
                </div>
              </div>
            </template>
            <!-- PDF 预览 -->
            <template v-else-if="currentFile.file_type === 'pdf'">
              <div class="pdf-preview">
                <iframe
                  :src="`/api/file-system/content?path=${encodeURIComponent(currentFile.file_path)}#toolbar=1&navpanes=1`"
                  type="application/pdf"
                  width="100%"
                  height="100%"
                  frameborder="0"
                ></iframe>
              </div>
            </template>
            <!-- Office 文档预览 -->
            <template v-else-if="['word', 'powerpoint', 'excel'].includes(currentFile.file_type)">
              <div class="office-preview">
                <div v-if="previewContent" class="preview-content" v-html="previewContent"></div>
                <div v-else class="loading-text">
                  <el-icon class="is-loading"><Loading /></el-icon>
                  加载中...
                </div>
              </div>
            </template>
            <!-- 其他文件类型 -->
            <template v-else>
              <div class="unknown-file">
                <el-icon :size="64">
                  <component :is="getFileIcon(currentFile)" />
                </el-icon>
                <p>该文件类型暂不支持预览</p>
                <el-button type="primary" @click="handleDownload">
                  下载文件
                </el-button>
              </div>
            </template>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加重命名对话框 -->
    <el-dialog
      v-model="renameDialog.visible"
      title="重命名"
      width="30%"
    >
      <el-form
        ref="renameFormRef"
        :model="renameDialog.form"
        :rules="renameDialog.rules"
        label-width="80px"
      >
        <el-form-item label="新名称" prop="newName">
          <el-input 
            v-model="renameDialog.form.newName"
            placeholder="请输入新名称"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="renameDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="confirmRename" :loading="renameDialog.loading">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加常用路径对话框 -->
    <el-dialog
      v-model="favoritePathDialog.visible"
      title="添加常用路径"
      width="30%"
    >
      <el-form
        ref="favoritePathFormRef"
        :model="favoritePathDialog.form"
        :rules="favoritePathDialog.rules"
        label-width="80px"
      >
        <el-form-item label="路径名称" prop="name">
          <el-input v-model="favoritePathDialog.form.name" />
        </el-form-item>
        <el-form-item label="路径" prop="path">
          <el-input 
            v-model="favoritePathDialog.form.path"
            placeholder="请输入或选择路径"
          >
            <template #append>
              <el-button @click="handleSelectPath">
                <el-icon><FolderOpened /></el-icon>
              </el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="favoritePathDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="addFavoritePath" :loading="favoritePathDialog.loading">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, reactive, onUnmounted, watch, h } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Folder, 
  FolderOpened, 
  Refresh,
  Back,
  Download, 
  Document, 
  Picture,
  Edit,
  Delete,
  Star,
  Plus,
  ArrowLeft,
  ArrowRight,
  Loading
} from '@element-plus/icons-vue'
import PreviewContent from '@/components/PreviewContent.vue'
import { formatFileSize } from '@/utils/format'
import type { FileInfo, FavoritePath } from '@/types/file'
import { request } from '@/utils/request'
import dayjs from 'dayjs'
import type { FormInstance } from 'element-plus'

interface DriveInfo {
  path: string;
  label: string;
  freeSpace: number;
  totalSpace: number;
  available: boolean;
}

const DEFAULT_PATH = 'H:\\'
const loading = ref(false)
const loadingContents = ref(false)
const fileList = ref<FileInfo[]>([])
const currentFile = ref<FileInfo | null>(null)
const folderContents = ref<FileInfo[]>([])
const currentPath = ref(DEFAULT_PATH)

// 添加盘符相关的状态
const drives = ref<DriveInfo[]>([])
const currentDrive = ref('H:\\')

// 添加显示隐藏文件的状态
const showHidden = ref(false)

// 添加常用路径相关的状态
const favoritePaths = ref<FavoritePath[]>([])
const favoritePathDialog = reactive({
  visible: false,
  loading: false,
  form: {
    name: '',
    path: ''
  },
  rules: {
    name: [
      { required: true, message: '请输入路径名称', trigger: 'blur' }
    ],
    path: [
      { required: true, message: '请输入路径', trigger: 'blur' },
      { 
        validator: async (rule: any, value: string, callback: Function) => {
          try {
            // 验证路径是否存在
            const response = await request(`/api/file-system/validate-path?path=${encodeURIComponent(value)}`)
            if (response.status === 'success') {
              callback()
            } else {
              callback(new Error('路径不存在'))
            }
          } catch (error) {
            callback(new Error('径无效'))
          }
        },
        trigger: 'blur'
      }
    ]
  }
})

// 获取文件扩展名
const getFileExtension = computed(() => {
  if (!currentFile.value || currentFile.value.is_dir) return ''
  const ext = currentFile.value.name.split('.').pop()?.toLowerCase() || ''
  return ext ? `.${ext}` : ''
})

// 根据文件类型获取标签类型
const getFileExtensionType = (fileType: string | undefined) => {
  if (!fileType) return 'info'
  
  const typeMap: Record<string, string> = {
    'text': '',  // 默认蓝色
    'image': 'success',  // 绿色
    'pdf': 'danger',  // 红色
    'word': 'primary',  // 主题色
    'excel': 'success',  // 绿色
    'powerpoint': 'warning',  // 橙色
    'directory': '',
    'unknown': 'info'
  }
  
  return typeMap[fileType] || 'info'
}

// 修改标题中的扩展名标签类型获取方式
const getFileExtensionTagType = computed(() => {
  if (!currentFile.value) return 'info'
  return getFileExtensionType(currentFile.value.file_type)
})

// 修改预览标题的计算属性
const getPreviewTitle = computed(() => {
  if (!currentFile.value) return '文件预览'
  return currentFile.value.name
})

// 获取目录内容
const fetchFiles = async (path: string = DEFAULT_PATH) => {
  loading.value = true
  try {
    const encodedPath = encodeURIComponent(path)
    const data = await request(`/api/file-system/list?path=${encodedPath}`)
    if (data.status === 'success') {
      fileList.value = data.data
      currentPath.value = path
      if (path !== currentFile.value?.file_path) {
        currentFile.value = null
      }
    } else {
      ElMessage.error(data.message || '获取文件列表失败')
    }
  } catch (error) {
    console.error('Error fetching files:', error)
    ElMessage.error('获取文件列表失败')
  } finally {
    loading.value = false
  }
}

// 获取文件夹内容
const fetchFolderContents = async (path: string) => {
  loadingContents.value = true
  try {
    const response = await fetch(`/api/file-system/list?path=${encodeURIComponent(path)}`)
    const data = await response.json()
    if (data.status === 'success') {
      folderContents.value = data.data
    }
  } catch (error) {
    ElMessage.error('获取文件夹内容失败')
  } finally {
    loadingContents.value = false
  }
}

// 添加预览内容的状态
const previewContent = ref('')

// 修改文件点击处理函数
const handleFileClick = async (file: FileInfo) => {
  currentFile.value = file
  previewContent.value = ''  // 清空之前的预览内容

  if (file.is_dir) {
    fetchFolderContents(file.file_path)
    return
  }

  // 获取文件预览内容
  try {
    const response = await request(`/api/file-system/content?path=${encodeURIComponent(file.file_path)}`)
    if (response.status === 'success' && response.data) {
      if (file.file_type === 'image') {
        return // 图片文件由 el-image 组件处理
      }
      previewContent.value = response.data.preview_data || '文件内容为空'
    } else {
      previewContent.value = '预览失败：' + (response.message || '未知错误')
    }
  } catch (error) {
    console.error('Error fetching preview:', error)
    previewContent.value = '预览失败：无法加载文件内容'
  }
}

// 修改文件双击处理函数，��需要清空预览内容
const handleFileDblClick = (file: FileInfo) => {
  if (file.is_dir) {
    previewContent.value = ''  // 清空预览内容
    fetchFiles(file.file_path)
  }
}

// 返回上级目录
const navigateUp = () => {
  const parentPath = currentPath.value.split('\\').slice(0, -1).join('\\')
  // 如果已经达盘符根目录，不再往上
  if (parentPath.endsWith(':')) {
    navigateTo(parentPath + '\\')
  } else if (parentPath) {
    navigateTo(parentPath)
  }
}

// 导航到指定路径
const navigateTo = (path: string) => {
  const normalizedPath = path.replace(/\//g, '\\')
  fetchFiles(normalizedPath)
}

// 预览指定文件
const previewFile = (file: FileInfo) => {
  currentFile.value = file
}

// 刷新当前目录
const refreshFiles = () => {
  fetchFiles(currentPath.value)
}

// 格式化日期
const formatDate = (timestamp: number) => {
  return dayjs(timestamp).format('YYYY-MM-DD HH:mm')
}

// 获取文件图标
const getFileIcon = (file: FileInfo) => {
  if (file.is_dir) return Folder
  switch (file.file_type) {
    case 'image':
      return Picture
    case 'text':
      return Document
    default:
      return Document
  }
}

// 下载文件
const handleDownload = () => {
  if (currentFile.value && !currentFile.value.is_dir) {
    window.open(`/api/file-system/download?path=${encodeURIComponent(currentFile.value.file_path)}`)
  }
}

// 在资源管理器中打开
const openInExplorer = async () => {
  if (!currentFile.value) return
  try {
    await fetch('/api/file-system/open-location', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ path: currentFile.value.file_path })
    })
  } catch (error) {
    ElMessage.error('打开文件位置失败')
  }
}

// 获取系统盘符信息
const fetchDrives = async () => {
  try {
    const response = await request('/api/file-system/drives')
    if (response.status === 'success') {
      drives.value = response.data
    }
  } catch (error) {
    console.error('Error fetching drives:', error)
    ElMessage.error('获取磁盘信息失败')
  }
}

// 处理盘符切换
const handleDriveChange = (drive: string) => {
  currentDrive.value = drive
  currentPath.value = drive
  fetchFiles(drive)
}

// 修改过滤文件列表的逻辑
const filteredFileList = computed(() => {
  if (showHidden.value) {
    return fileList.value
  }
  // 过滤掉以.开头的文件和文件夹
  return fileList.value.filter(file => !file.name.startsWith('.'))
})

// 修改件夹内容的过滤
const filteredFolderContents = computed(() => {
  if (showHidden.value) {
    return folderContents.value
  }
  return folderContents.value.filter(file => !file.name.startsWith('.'))
})

// 修改初始化逻辑
onMounted(async () => {
  await fetchDrives()
  // 默认选择 H 盘
  const hDrive = drives.value.find(d => d.path.startsWith('H:'))
  if (hDrive && hDrive.available) {
    currentDrive.value = hDrive.path
    currentPath.value = hDrive.path
    fetchFiles(hDrive.path)
  } else {
    // 如果 H 盘不可用，选择第一个可用的盘符
    const availableDrive = drives.value.find(d => d.available)
    if (availableDrive) {
      currentDrive.value = availableDrive.path
      currentPath.value = availableDrive.path
      fetchFiles(availableDrive.path)
    }
  }
  // 获取常用路径列表
  fetchFavoritePaths()
})

// 重命名对话框状态
const renameDialog = reactive({
  visible: false,
  loading: false,
  currentFile: null as FileInfo | null,
  form: {
    newName: ''
  },
  rules: {
    newName: [
      { required: true, message: '请输入新名称', trigger: 'blur' },
      { 
        validator: (rule: any, value: string, callback: Function) => {
          if (value.includes('/') || value.includes('\\')) {
            callback(new Error('名称不能包含斜杠'))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ]
  }
})

const renameFormRef = ref<FormInstance>()

// 处理重命名
const handleRename = (file: FileInfo) => {
  renameDialog.currentFile = file
  renameDialog.form.newName = file.name
  renameDialog.visible = true
}

// 确认重命名
const confirmRename = async () => {
  renameDialog.loading = true
  try {
    const response = await request('/api/file-system/rename', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        old_path: renameDialog.currentFile?.file_path,
        new_name: renameDialog.form.newName
      })
    })
    if (response.status === 'success') {
      ElMessage.success('重命名成功')
      fetchFiles(currentPath.value)
      renameDialog.visible = false
    } else {
      ElMessage.error(response.message || '重命名失败')
    }
  } catch (error) {
    console.error('Error renaming file:', error)
    ElMessage.error('重命名失败')
  } finally {
    renameDialog.loading = false
  }
}

// 修改删除处理函数
const handleDelete = async (file: FileInfo) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除${file.is_dir ? '文件夹' : '文件'} "${file.name}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 修改请求方式
    const response = await request(`/api/file-system/delete?path=${encodeURIComponent(file.file_path)}`, {
      method: 'DELETE'
    })

    if (response.status === 'success') {
      ElMessage.success('删除成功')
      // 如果删除的是当前预览的文件，清除预览
      if (currentFile.value?.file_path === file.file_path) {
        currentFile.value = null
      }
      fetchFiles(currentPath.value)
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {  // 忽略取消操作的错误
      console.error('Error deleting file:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 获取常用路径列表
const fetchFavoritePaths = async () => {
  try {
    // 先尝试初始化默认路径
    await request('/api/file-system/favorite-paths/init', {
      method: 'POST'
    })
    
    // 然后获取路径列表
    const response = await request('/api/file-system/favorite-paths')
    if (response.status === 'success') {
      favoritePaths.value = response.data
    }
  } catch (error) {
    console.error('Error fetching favorite paths:', error)
    ElMessage.error('获取常用径失败')
  }
}

// 显示添加路径对话框
const showAddPathDialog = () => {
  favoritePathDialog.form.path = currentPath.value
  favoritePathDialog.form.name = ''
  favoritePathDialog.visible = true
}

// 添加用路径
const addFavoritePath = async () => {
  favoritePathDialog.loading = true
  try {
    const response = await request('/api/file-system/favorite-paths', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(favoritePathDialog.form)
    })
    
    if (response.status === 'success') {
      ElMessage.success('添加成功')
      favoritePaths.value.push(response.data)
      favoritePathDialog.visible = false
    }
  } catch (error) {
    ElMessage.error('添加失败')
  } finally {
    favoritePathDialog.loading = false
  }
}

// 删除常用路径
const deleteFavoritePath = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除此常用路径吗？', '删除确认', {
      type: 'warning'
    })
    
    const response = await request(`/api/file-system/favorite-paths/${id}`, {
      method: 'DELETE'
    })
    
    if (response.status === 'success') {
      ElMessage.success('删除成功')
      favoritePaths.value = favoritePaths.value.filter(p => p.id !== id)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 处理选择路径
const handleSelectPath = async () => {
  try {
    const response = await request('/api/file-system/select-folder', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ 
        initial_path: favoritePathDialog.form.path || currentPath.value 
      })
    })
    
    if (response.status === 'success' && response.data?.path) {
      favoritePathDialog.form.path = response.data.path
    }
  } catch (error) {
    ElMessage.error('选择路径失败')
  }
}

// 获取文件夹中的图片URL列表
const folderImageUrls = computed(() => {
  return folderContents.value
    .filter(file => file.file_type === 'image')
    .map(file => `/api/file-system/content?path=${encodeURIComponent(file.file_path)}`)
})

// 获取图片在文件夹图片列表中的索引
const getFolderImageIndex = (file: FileInfo) => {
  return folderContents.value
    .filter(f => f.file_type === 'image')
    .findIndex(f => f.file_path === file.file_path)
}

// 处理预览项目点击
const handlePreviewItem = async (item: FileInfo) => {
  if (item.is_dir) {
    previewFile(item)
    return
  }

  if (item.file_type === 'image') {
    return
  }

  // 如果是可预览的文件类型，弹出预览对话框
  if (['text', 'word', 'powerpoint', 'excel', 'pdf'].includes(item.file_type)) {
    try {
      // 如果是 PDF，使用 iframe 预览
      if (item.file_type === 'pdf') {
        ElMessageBox.alert(
          h('div', { 
            class: 'preview-dialog-content pdf-preview-content',
          }, [
            h('iframe', {
              src: `/api/file-system/content?path=${encodeURIComponent(item.file_path)}#toolbar=1&navpanes=1`,
              style: {
                width: '100%',
                height: '100%',
                border: 'none'
              }
            })
          ]), 
          item.name,
          {
            customClass: 'preview-dialog pdf-preview-dialog',
            dangerouslyUseHTMLString: true,
            showClose: true,
            closeOnClickModal: true,
            closeOnPressEscape: true
          }
        )
        return
      }

      const response = await request(`/api/file-system/content?path=${encodeURIComponent(item.file_path)}`)
      if (response.status === 'success' && response.data) {
        const previewData = response.data.preview_data || '文件内容为空'

        // 打开预览对话框
        ElMessageBox.alert(
          h('div', { 
            class: 'preview-dialog-content',
            style: {
              maxHeight: '70vh',
              overflow: 'auto'
            }
          }, [
            // 如果是文本文件，添加复制按钮
            item.file_type === 'text' && h('div', { class: 'text-actions' }, [
              h('el-button', {
                type: 'primary',
                size: 'default',  // 改为默认大小
                onClick: () => {
                  navigator.clipboard.writeText(previewData)
                  ElMessage.success('已复制到剪贴板')
                }
              }, [
                h('el-icon', { class: 'copy-icon' }, [h('Document')]),
                '复制全部'
              ])
            ]),
            h('div', { 
              class: 'preview-content',
              innerHTML: previewData
            })
          ]), 
          item.name,
          {
            customClass: `preview-dialog ${item.file_type}-preview-dialog`,
            dangerouslyUseHTMLString: true,
            showClose: true,
            closeOnClickModal: true,
            closeOnPressEscape: true
          }
        )
      } else {
        ElMessage.error('预览失败：' + (response.message || '未知错误'))
      }
    } catch (error) {
      console.error('Error fetching preview:', error)
      ElMessage.error('预览失败：无法加载文件内容')
    }
  }
}

// 获取当前图片在列表中的索引
const currentImageIndex = computed(() => {
  if (!currentFile.value) return 0
  return fileList.value
    .filter(f => f.file_type === 'image')
    .findIndex(f => f.file_path === currentFile.value?.file_path)
})

// 获取当前目录下的总图片数
const totalImages = computed(() => {
  return fileList.value.filter(f => f.file_type === 'image').length
})

// 是否有上一张图片
const hasPrevImage = computed(() => {
  return currentImageIndex.value > 0
})

// 是否有下一张图片
const hasNextImage = computed(() => {
  return currentImageIndex.value < totalImages.value - 1
})

// 显示上一张图片
const showPrevImage = () => {
  if (!hasPrevImage.value) return
  const imageFiles = fileList.value.filter(f => f.file_type === 'image')
  const prevImage = imageFiles[currentImageIndex.value - 1]
  currentFile.value = prevImage
}

// 显示下一张图片
const showNextImage = () => {
  if (!hasNextImage.value) return
  const imageFiles = fileList.value.filter(f => f.file_type === 'image')
  const nextImage = imageFiles[currentImageIndex.value + 1]
  currentFile.value = nextImage
}

// 添加键盘事件监听
onMounted(() => {
  window.addEventListener('keydown', handleKeyDown)
})

onUnmounted(() => {
  window.removeEventListener('keydown', handleKeyDown)
})

const handleKeyDown = (e: KeyboardEvent) => {
  if (currentFile.value?.file_type !== 'image') return
  
  if (e.key === 'ArrowLeft') {
    showPrevImage()
  } else if (e.key === 'ArrowRight') {
    showNextImage()
  }
}

// 获取不带扩展名的文件名
const getFileNameWithoutExt = (filename: string) => {
  const lastDotIndex = filename.lastIndexOf('.')
  return lastDotIndex === -1 ? filename : filename.slice(0, lastDotIndex)
}

// 获取文件扩展名
const getFileExt = (filename: string) => {
  const ext = filename.split('.').pop()?.toLowerCase() || ''
  return ext ? `.${ext}` : ''
}
</script>

<style lang="scss" scoped>
.preview-page {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;

  .control-panel {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .drive-selector {
      flex: 1;
      margin-right: 20px;
    }

    .favorite-paths {
      margin: 0 16px;
    }

    .show-hidden-switch {
      flex-shrink: 0;
    }
  }

  .content-area {
    flex: 1;
    min-height: 0;  // 确保flex布正常工作
  }

  .current-path {
    margin: 10px 0;
    padding: 5px;
    background-color: var(--el-fill-color-light);
    border-radius: 4px;
    font-size: 12px;
    color: var(--el-text-color-secondary);
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .file-list {
    height: calc(100vh - 100px);

    .mb-3 {
      margin-bottom: 12px;
    }
  }

  .preview-area {
    height: calc(100vh - 100px);

    .empty-preview {
      height: calc(100vh - 200px);
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .preview-content {
      height: calc(100vh - 200px);
      overflow: auto;
      width: 705px;
    }
  }

  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    
    .file-size {
      margin-left: auto;
      color: #909399;
      font-size: 12px;
    }
  }

  .is-folder {
    color: var(--el-color-primary);
    font-weight: bold;
  }

  .el-table {
    // 添加鼠标悬停效果
    :deep(tr) {
      cursor: pointer;
      &:hover {
        background-color: var(--el-fill-color-light);
      }
    }

    // 图标样式
    .el-icon {
      font-size: 18px;
      vertical-align: middle;
    }
  }
}

.preview-area {
  height: calc(100vh - 100px);
  
  .folder-preview {
    height: calc(100vh - 200px);
    overflow-y: auto;
    padding: 20px;

    .file-item {
      border: 1px solid var(--el-border-color);
      border-radius: 4px;
      padding: 10px;
      margin-bottom: 20px;
      cursor: pointer;
      transition: all 0.3s;
      text-align: center;

      &:hover {
        background-color: var(--el-fill-color-light);
        transform: translateY(-2px);
        box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
      }

      .thumbnail {
        width: 100%;
        height: 100px;
        display: flex;
        align-items: center;
        justify-content: center;
        overflow: hidden;
        
        .el-image {
          width: 100%;
          height: 100px;
          border-radius: 4px;
          cursor: zoom-in;
        }
      }

      .file-info-wrapper {
        margin: 8px 0;
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 4px;

        .file-name {
          font-size: 14px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          width: 100%;
          text-align: center;
        }

        .file-ext-tag {
          font-family: monospace;
          text-transform: lowercase;
          font-size: 11px;
          height: 20px;
          line-height: 18px;
          padding: 0 6px;
          font-weight: bold;  // 加粗
          
          // 自定义标签颜色
          &.el-tag--primary {
            --el-tag-bg-color: var(--el-color-primary-light-9);
            --el-tag-border-color: var(--el-color-primary);
            --el-tag-text-color: var(--el-color-primary);
            border-width: 1.5px;  // 加粗边框
          }
          
          &.el-tag--success {
            --el-tag-bg-color: var(--el-color-success-light-9);
            --el-tag-border-color: var(--el-color-success);
            --el-tag-text-color: var(--el-color-success);
            border-width: 1.5px;
          }
          
          &.el-tag--warning {
            --el-tag-bg-color: var(--el-color-warning-light-9);
            --el-tag-border-color: var(--el-color-warning);
            --el-tag-text-color: var(--el-color-warning);
            border-width: 1.5px;
          }
          
          &.el-tag--danger {
            --el-tag-bg-color: var(--el-color-danger-light-9);
            --el-tag-border-color: var(--el-color-danger);
            --el-tag-text-color: var(--el-color-danger);
            border-width: 1.5px;
          }
          
          &.el-tag--info {
            --el-tag-bg-color: var(--el-color-info-light-9);
            --el-tag-border-color: var(--el-color-info);
            --el-tag-text-color: var(--el-color-info);
            border-width: 1.5px;
          }
        }
      }

      .file-info {
        margin-top: 4px;
        font-size: 12px;
        color: var(--el-text-color-secondary);
        display: flex;
        justify-content: space-between;
        width: 100%;
      }
    }
  }

  .file-preview {
    height: calc(100vh - 200px);
    overflow: auto;
    padding: 20px;

    .image-preview {
      display: flex;
      flex-direction: column;
      align-items: center;
      height: 100%;
      
      .image-actions {
        display: flex;
        align-items: center;
        gap: 20px;
        margin-bottom: 20px;
        width: 100%;
        
        .el-image {
          flex: 1;
          height: calc(100vh - 300px);
        }
        
        .el-button {
          opacity: 0.7;
          transition: opacity 0.3s;
          
          &:hover {
            opacity: 1;
          }
          
          &.is-disabled {
            opacity: 0.3;
          }
        }
      }
      
      .image-info {
        margin-top: 10px;
        color: var(--el-text-color-secondary);
        font-size: 14px;
      }
    }

    .text-preview {
      pre {
        margin: 0;
        padding: 16px;
        background-color: var(--el-fill-color-light);
        border-radius: 4px;
        font-family: monospace;
        white-space: pre-wrap;
        word-break: break-all;
        max-height: calc(100vh - 250px);
        overflow: auto;
      }

      .loading-text {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100%;
        color: var(--el-text-color-secondary);
        gap: 8px;
      }
    }

    .pdf-preview,
    .office-preview {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 100%;
      gap: 16px;

      .preview-message {
        color: var(--el-text-color-secondary);
        text-align: center;
        margin-bottom: 20px;
      }
    }

    .unknown-file {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 100%;
      gap: 16px;
      color: var(--el-text-color-secondary);
    }
  }
}

.el-dropdown-menu {
  .el-space {
    width: 100%;
    justify-content: space-between;
  }
}

.pdf-preview {
  height: calc(100vh - 200px);
  
  iframe {
    background-color: var(--el-bg-color);
    border-radius: 4px;
  }
}

.office-preview {
  height: calc(100vh - 200px);
  overflow: auto;
  padding: 20px;
  background-color: white;
  
  .preview-content {
    :deep(*) {
      max-width: 100%;
      font-family: var(--el-font-family);
    }
    
    :deep(img) {
      max-width: 100%;
      height: auto;
    }
    
    :deep(table) {
      border-collapse: collapse;
      width: 100%;
      margin: 10px 0;
      
      td, th {
        border: 1px solid #ddd;
        padding: 8px;
      }
    }
  }
  
  .loading-text {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    color: var(--el-text-color-secondary);
    gap: 8px;
  }
}

.preview-title {
  display: flex;
  align-items: center;
  gap: 8px;
  
  .file-extension {
    font-family: monospace;
    text-transform: lowercase;
    font-size: 12px;
    height: 22px;
    line-height: 20px;
  }
}

.office-preview {
  .preview-content {
    :deep(.excel-preview) {
      .excel-table {
        td, th {
          &:hover {
            // 显示完整内容
            overflow: visible;
            white-space: normal;
            word-break: break-word;
            background-color: #ecf5ff;
            z-index: 2;
            position: relative;
          }
        }
      }
    }
  }
}

.preview-dialog {
  width: 90% !important;
  max-width: 1600px;
  margin: 15vh auto 0 !important;
  
  :deep(.el-message-box__header) {
    padding: 15px 20px;
    border-bottom: 1px solid var(--el-border-color-light);
  }
  
  :deep(.el-message-box__content) {
    padding: 0;
    // max-height: 70vh;
    overflow: hidden;
  }
  
  .preview-dialog-content {
    height: 70vh;
    padding: 0;
    display: flex;
    flex-direction: column;
    
    .text-actions {
      padding: 10px 20px;
      border-bottom: 1px solid var(--el-border-color-light);
      background: #f8f9fa;
      display: flex;
      justify-content: flex-end;  // 按钮靠右对齐
      
      .el-button {
        background-color: var(--el-color-primary-light-9);
        border-color: var(--el-color-primary-light-7);
        font-weight: bold;
        
        &:hover {
          background-color: var(--el-color-primary-light-8);
        }
      }
    }
    
    .preview-content {
      flex: 1;
      overflow: auto;
      padding: 20px;
      font-family: monospace;
      white-space: pre-wrap;
      word-break: break-all;

      // Office 文档样式
      :deep(.word-preview),
      :deep(.excel-preview) {
        padding: 20px;
        background: white;
        min-height: 100%;

        // Excel 表格样式
        .excel-table {
          width: 100%;
          min-width: 2400px;  // 增加最小宽度到 2400px
          
          th, td {
            min-width: 200px;  // 增加单元格最小宽度到 200px
            padding: 12px;
            
            &:hover {
              overflow: visible;
              white-space: normal;
              word-break: break-word;
              background-color: #ecf5ff;
              z-index: 2;
              position: relative;
            }
          }
          
          thead th {
            position: sticky;
            top: 0;
            background: #f5f7fa;
            z-index: 1;
          }
        }
      }

      // Word 文档样式
      :deep(.word-preview) {
        max-width: 1200px;
        margin: 0 auto;
        padding: 40px;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
      }
    }
    
    // PDF 预览样式
    .pdf-preview {
      flex: 1;
      height: 100%;
      overflow: hidden;
      background: #525659;
      
      iframe {
        border: none;
        width: 100%;
        height: 100%;
        background: white;
      }
    }
  }
}

// 为不同类型的预览设置不同的宽度
.excel-preview-dialog {
  width: 99% !important;  // 增加到 99%
  max-width: 3000px !important;  // 增加最大宽度
  
  .preview-dialog-content {
    .preview-content {
      padding: 10px;  // 减小内边距以显示更多内容
      
      :deep(.excel-preview) {
        .excel-table {
          min-width: 2800px;  // 增加表格最小宽度
          
          th, td {
            min-width: 220px;  // 增加单元格最小宽度
          }
        }
      }
    }
  }
}

// PDF 预览对话框样式
.pdf-preview-dialog {
  position: fixed !important;  // 使用固定定位
  top: 15% !important;  // 距离顶部 15%
  left: 15% !important;  // 距离左侧 15%
  width: 70% !important;  // 宽度占屏幕 70%
  height: 70% !important;  // 高度占屏幕 70%
  margin: 0 !important;  // 移除外边距
  
  :deep(.el-message-box__header) {
    padding: 10px 20px;
    border-bottom: 1px solid var(--el-border-color-light);
    background: #f8f9fa;
    
    .el-message-box__title {
      font-size: 16px;
      font-weight: bold;
    }
    
    .el-message-box__headerbtn {
      top: 12px;
    }
  }
  
  :deep(.el-message-box__content) {
    padding: 0;
    height: calc(100% - 53px) !important;  // 减去头部高度
    max-height: none !important;
  }
  
  .pdf-preview-content {
    height: 100% !important;
    background: #525659;
    
    iframe {
      width: 100%;
      height: 100%;
      border: none;
      background: white;
    }
  }
}

// 修改全局预览对话框样式
:deep(.el-message-box__wrapper) {
  overflow: hidden;
  
  .el-message-box {
    &.pdf-preview-dialog {
      position: fixed !important;  // 使用固定定位
      transform: none !important;
      margin: 0 !important;
    }
  }
}
</style> 